const MD5Utils = require('MD5.js');

function formatNumber(n) {
  const num = n.toString();
  return num[1] ? num : `0${num}`;
}

function formatTime(date, type) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  let time = '';
  switch (type) {
    case 1:
      time = `${[year, month, day].map(formatNumber).join('.')}`;
      break;
    case 2:
      time = `${[year, month, day].map(formatNumber).join('.')} ${[hour, minute].map(formatNumber).join(':')}`;
      break;
    default:
      time = `${[year, month, day].map(formatNumber).join('.')} ${[hour, minute, second].map(formatNumber).join(':')}`;
  }
  return time;
}

function getSign(data,security_code) {
  var newkey = Object.keys(data).sort();
  var sign = "";

  for (var i = 0; i < newkey.length; i++) {//遍历newObj数组
    if (i != newkey.length - 1) {
      sign += newkey[i];
      sign += "=";
      sign += data[newkey[i]];
      sign += "&";
    } else {
      sign += newkey[i];
      sign += "=";
      sign += data[newkey[i]];
    }

  }
  sign += security_code;

  return MD5Utils.hexMD5(sign);
}

//导出接口--必须要写 
module.exports = {
  formatNumber,
  formatTime,
  getSign,
};
